package com.sharemarking.application.common.controller;

import java.io.IOException;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sharemarking.application.common.BaseSpecification;
import com.sharemarking.application.common.entity.Comment;
import com.sharemarking.application.common.repository.CommentRepo;

@Controller
@RequestMapping("comment")
public class CommentController {
	
	@Autowired
	private CommentRepo cr;
	
	/**
	 * 评论数据列表页
	 * 
	 * @param page
	 * @param size
	 * @param model
	 */
	@GetMapping(value = "index")
	@PreAuthorize("hasPermission('sys:comment',1)")
	public void index(Comment e, Integer page, Integer size, Model model) {
		if (page == null) {
			page = 0;
		} else {
			page -= 1;
		}
		if (size == null) {
			size = 10;
		}
		// 按照id降序
		Sort sort = new Sort(Direction.DESC, "id");
		PageRequest req = new PageRequest(page, size, sort);
		Page<Comment> p = cr.findAll(new BaseSpecification<Comment>(e), req);
		model.addAttribute("page", p);
		model.addAttribute("search", e);
	}
	
	
	/**
	 * 获取实体接口
	 * 
	 * @param obj
	 * @param model
	 * @return
	 */
	@GetMapping(value = "{id}")
	@PreAuthorize("hasPermission('sys:comment',1)")
	public String get(Comment obj, Model model) {
		if (obj.getId() != 0)
			obj = cr.findOne(obj.getId());
		model.addAttribute("obj", obj);

		return "comment/form";
	}
	

	/**
	 * 评论添加和编辑
	 * 
	 * @return
	 * @throws IOException
	 */
	@PostMapping(value = "{id}")
	@Transactional
	@PreAuthorize("hasPermission('sys:comment',#target.id==0?8:4)")
	public String index(Comment target) throws IOException {
	
			// 添加
			if (target.getId() == 0) {
				
				cr.save(target);

				return "redirect:index";
			}
			// 编辑
			else {
				Comment resource = cr.findOne(target.getId());
				if (resource == null) {
					return null;
				}
			 
						
			}
		return "redirect:index";
	}
	
	//删除资源信息
	@GetMapping(value="{id}/delete")
	@Transactional
	public String delete(@PathVariable("id") Integer id){
		 cr.findOne(id).setDelFlag(true);
		 return "redirect:../index";
	}
	
	

	
}
